import { Component, OnInit } from '@angular/core';
import {
  FormGroup,
  FormBuilder
} from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';

import { User } from './model/user';
import { I18NService } from '@core/i18n/i18n.service';
import { PopupService } from '@shared/popup/popup.service';
import { UserService } from './service/user.service';

import { UserModifyComponent } from './modify/user-modify.component';

@Component({
  styles: [],
  templateUrl: './user-list.html'
})

export class UserListComponent implements OnInit {

  data: User[] = [];

  _loading = false;

  page = {
    pageNo: 1,
    pageSize: 10,
    total: 1
  };

  validateForm: FormGroup;

  constructor(
    private fb: FormBuilder,
    private i18nService: I18NService,
    private userService: UserService,
    private message: NzMessageService,
    private popupService: PopupService
  ) {
    this.validateForm = this.fb.group({
      account: null
    });
  }

  ngOnInit(): void {
    this.getAllUsers();
  }

  getAllUsers(reset = false): void {
    this._loading = true;
    if (reset) {
      this.page.pageNo = 1;
    }
    this.userService.getAllUsers(this.page.pageNo, this.page.pageSize)
      .subscribe(res => {
        this.data = res.records;
        this.page.total = res.total;
        this._loading = false;
      }, err => {
        this._loading = false;
      });
  }

  showModify(item?: any): void {
    let params = {};
    let title = '添加用户';
    if (item !== undefined) {
      params = {
        id: item.id
      };
      title = item.account + '用户修改';
    }
    this.popupService.create({
      title: title,
      content: UserModifyComponent,
      componentParams: params,
      width: 620,
      onSubmit: (res) => {
        this.getAllUsers(true);
      },
      onCancel: (res) => { }
    }).afterClose.subscribe(res => { });
  }

  delete(id: number) {
    this.userService.deltetUser(id)
      .subscribe(res => {
        if (res) {
          this.message.success(this.i18nService.translate('modify.return.delete_success'));
          this.getAllUsers();
        } else {
          this.message.error(this.i18nService.translate('modify.return.delete_error'));
        }
      });
  }

  refresh(): void {
    this.getAllUsers(true);
  }

}
